﻿/*
Copyright (c) 2010 Lance Ward
This software is licensed under the MIT license, except where otherwise noted.
For complete license details, refer to license.txt
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using ADNLib;

namespace ADNCanvas
{
	public class ToolText : Tool
	{
		private bool capturing = false;

		public ToolText() { this.toolType = DrawingToolType.Text; }

		public override void MouseDown(PointF location, System.Windows.Forms.MouseButtons button, int clicks)
		{
            if (currentShape != null && !String.IsNullOrEmpty(currentShape.Text))
            {
                OnShapeComplete(true);
                OnToolComplete(true);
                capturing = false;
            }
            else
            {
                int index = HitTestObjects(location, typeof(ShapeText));
                if (index >= 0)
                {
                    currentShape = (Shape)xObjects[index];
                }
                else
                {
                    CreateShape(location);
                    capturing = true;
                }

                prevPoint = location;
            }
		}

		public override void MouseMove(PointF location, System.Windows.Forms.MouseButtons button, int clicks)
		{
			if (capturing)
			{
				prevPoint = location;
				if (currentShape != null) { currentShape.AppendPoint(location, true); }
			}
		}

		public override void MouseUp(PointF location, System.Windows.Forms.MouseButtons button, int clicks)
		{
			if (capturing)
			{
				prevPoint = location;
				currentShape.AppendPoint(location, true);
                capturing = false;
			}
		}

		public override void OnKeyDown(char keyChar, Keys modifiers, bool capsLock)
		{
			if (currentShape != null)
			{
                bool upper = false;
                if ((capsLock && modifiers != Keys.Shift) || (!capsLock && modifiers == Keys.Shift)) { upper = true; }
                if (upper) { this.currentShape.Text += keyChar.ToString().ToUpper(); }
                else { this.currentShape.Text += keyChar.ToString().ToLower(); }
			}
		}

		private void CreateShape(PointF startPoint)
		{
			currentShape = new ShapeText();
			currentShape.AppendPoint(startPoint, true);
			currentShape.FillColor = defaultFill.Clone();
			currentShape.LineColor = defaultLine.Clone();
		}

		public override Cursor GetToolCursor()
		{
			return Cursors.Cross;
		}

		protected override void OnShapeComplete(bool isComplete)
		{
			base.OnShapeComplete(isComplete);
		}

		protected override void OnToolComplete(bool isComplete)
		{
			base.OnToolComplete(isComplete);
		}
	}
}
